<?php

namespace App\Http\Controllers\Admin\Hotel;

use App\Constant\Constant;
use App\Http\Controllers\Admin\CommonController;
use App\Models\Hotel\HotelImage;
use App\Requests\HotelImage\StoreRequest;
use Illuminate\Http\Request;
use App\Exceptions\ExceptionSms;
use Carbon\Carbon;
use App\Helpers\MoneyHelper;

class HotelImageController extends CommonController
{
    protected $model = HotelImage::class;

    public function index()
    {
        $search_forms = HotelImage::getForms(['hotel_id', 'cat_id', 'type']);
        $search_forms['type']['value'] = 1;

        $cols = [[
            ['field' => 'hotel_name', 'title' => '酒店'],
            ['field' => 'cat_name', 'title' => '分类'],
            ['field' => 'image_format', 'title' => '图', 'escape' => false],
            ['field' => 'sort', 'title' => '排序'],
            ['field' => 'action', 'title' => '操作', 'templet' => '#list-bar'],
        ]];

        $permission_code = 'hotel-image-query';

        $uri = '/admin/hotel/image/list?code=' . $permission_code;

        $top_btns = [
            ['code' => 'hotel-image-add']
        ];

        $row_btns = [
            ['code' => 'hotel-image-edit'],
            ['code' => 'hotel-image-delete']
        ];

        return view('components.list', compact('search_forms', 'cols', 'permission_code', 'uri', 'top_btns', 'row_btns'));
    }

    public function dataList()
    {
        $list = HotelImage::bgBaseQuery($this->input())->paginate($this->limit);
        /** @var HotelImage $resource */
        foreach ($list as $resource) {
            $resource->image_format = $resource->formatImage($resource->image);
            $resource->hotel_name   = $resource->hotel->name;
            $resource->cat_name     = $resource->cat->name ?? "";
        }
        return ExceptionSms::homeList($list->items(), $list->total());
    }

    public function editAdd()
    {
        $id   = $this->input('id') ?? 0;
        $data = $id ? HotelImage::getOneById($id) : null;

        $save_forms                  = HotelImage::getForms(['hotel_id', 'type', 'cat_id', 'thumbnail', 'sort'], 'save');
        $save_forms['type']['value'] = 1;
        if ($data) {
            $save_forms['thumbnail']['value'] = $data->image;
        }

        $permission_code = $id ? 'hotel-image-edit-save' : 'hotel-image-add-save';

        return view('components.save_form', compact('data', 'save_forms', 'permission_code'));
    }

    public function dataSave(StoreRequest $request)
    {
        $id = $request->get('id') ?? "";
        if ($id) $data = HotelImage::getOneById($id);
        else $data = new HotelImage();
        $data->hotel_id = $request->get("hotel_id");
        $data->type     = $request->get("type");
        $data->image    = $request->get('thumbnail');
        $data->cat_id   = $request->get('cat_id');
        $data->sort     = $request->get('sort');
        $data->save();
        return ExceptionSms::returnSuccess();
    }
}
